﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WXWorkSvc.Common.TagHelpers;
[HtmlTargetElement("desk-detail", TagStructure = TagStructure.WithoutEndTag)]
public class DeskDetailTagHelper : TagHelper
{
    #region Consts
    /// <summary>
    /// 0:Display,1:Value
    /// </summary>
    const string DeskStringFormat = """
        <tr><th>{0}<th><td>{1}</td></tr>
        """;
    const string DeskStringFormatWarn = """
        <tr class="table-warning"><th>{0}<th><td>{1}</td></tr>
        """;
    #endregion
    private readonly IHtmlGenerator _HtmlGenerator;
    public DeskDetailTagHelper(IHtmlGenerator generator)
    {
        _HtmlGenerator = generator;
    }


    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; } = default!;
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-for-")]
    public Dictionary<string, ModelExpression> Fors { get; set; } = new();
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-warn-")]
    public Dictionary<string, string> Warns { get; set; } = new();
    /// <summary>
    /// 删除时保存的BindProperty
    /// </summary>
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-hidden-")]
    public Dictionary<string, ModelExpression> Hiddens { get; set; } = new();
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;


        var tagBuilder = new TagBuilder("table");
        tagBuilder.AddCssClass("table table-striped table-hover");
        foreach (var kv in Fors)
        {
            var sf = Warns.ContainsKey(kv.Key) ? DeskStringFormatWarn : DeskStringFormat;
            var value = kv.Value.Model is bool bb ? (bb ? "是" : "否") : kv.Value.Model?.ToString();
            tagBuilder.InnerHtml.AppendHtml(string.Format(sf, kv.Value.GetDisplayName(), value));
        }
        output.Content.AppendHtml(tagBuilder);

        if (Hiddens.Count > 0)
        {
            foreach (var kv in Hiddens)
                output.Content.AppendHtml(_HtmlGenerator.GenerateHidden(ViewContext, kv.Value.ModelExplorer, kv.Value.Name, kv.Value.Model, false, null));
        }

    }
}
